<?php namespace App\Admin\Base;

use Requests, Log;

trait SyncCacheService {
    
    public $withSyncCache = true;
    
    protected function syncCache(){
        if(!$this->withOpLog){
            return ;
        }
        $operation = $this->getCurrentOperation();
        $logConfig = $operation->log_config ? json_decode($operation->log_config, true) : [];
        if(!$logConfig || !isset($logConfig['data_source']) || !$logConfig['data_source']){
            return $this;
        }
        $dataSource = $logConfig['data_source'];
        $idName = $logConfig['data_id'];
        $data = [];
        $needs = ['user', 'comment', 'content', 'topic', 'program'];
        switch ($dataSource) {
            case '3' : //创建模型
                if($this->createModel){
                    $data[] = [
                        'table' => $this->createModel->getTable(),
                        'action' => 'add',
                        'id' => $this->createModel->{$idName}
                    ];
                }
                break;
            case '4' : //编辑模型
                if($this->updateModel){
                    $data[] = [
                        'table' => $this->updateModel->getTable(),
                        'action' => 'update',
                        'id' => $this->updateModel->{$idName}
                    ];
                }
                break;
            case '5' : //修改模型
                foreach($this->changeModels as $model){
                    $data[] = [
                        'table' => $model->getTable(),
                        'action' => 'update',
                        'id' => $model->{$idName}
                    ];
                }
                break;
            case '6' : //删除模型
                foreach($this->deleteModels as $model){
                    $data[] = [
                        'table' => $model->getTable(),
                        'action' => 'delete',
                        'id' => $model->{$idName}
                    ];
                }
                break;
        }
        foreach($data as $key => $item){
            if(!in_array($item['table'], $needs)){
                unset($data[$key]);
            }
        }
        if(count($data) > 0){
            $this->syncCacheSendRequest($data);
        }
    }
    
    protected function syncCacheSendRequest($dataRaw){
        $data = ['type' => 'database', 'data' => $dataRaw];
        $url = env('API_URL').'/sendMessageToApi';
        $response = Requests::post($url, [], ['message' => $this->toJson($data)]);
        if($response->status_code == 200){
            $responseJson = json_decode($response->body, true);
            if($responseJson['statusCode'] != '0'){
                throw new \Exception('更新缓存失败-'.$responseJson['message']);
            }
        }else{
            throw new \Exception('请求失败');
        }
    }
}